# -*- coding: utf-8 -*-
# Author   : ZhangQing
# Time     : 2025-08-12 12:00
# File     : app_config.py
# Project  : codebuddy_craft
# Desc     : 应用启动配置

"""
应用启动配置 🚀

集成所有优化功能，配置应用启动参数
"""

import logging
import asyncio
from typing import List, Dict, Any, Optional

from fastapi import FastAPI, Depends
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.responses import JSONResponse

from backend.core.settings import settings
from backend.utils.logger import setup_logging, get_system_logger
from backend.api.error_handlers import setup_error_handlers
from backend.api.security_middleware import setup_security_middleware
from backend.database.connection import init_db, close_db_connections

logger = logging.getLogger(__name__)
system_logger = get_system_logger()


def create_app() -> FastAPI:
    """创建FastAPI应用实例 🏗️

    Returns:
        FastAPI应用实例
    """
    # 设置日志
    setup_logging(settings)
    
    # 创建FastAPI应用
    app = FastAPI(
        title=settings.PROJECT_NAME,
        description=settings.PROJECT_DESCRIPTION,
        version=settings.PROJECT_VERSION,
        docs_url=settings.DOCS_URL if not settings.is_production else None,
        redoc_url=settings.REDOC_URL if not settings.is_production else None,
        openapi_url=settings.OPENAPI_URL if not settings.is_production else None,
    )
    
    # 设置安全中间件
    setup_security_middleware(app)
    
    # 设置错误处理器
    setup_error_handlers(app)
    
    # 注册启动和关闭事件
    register_events(app)
    
    # 注册路由
    register_routers(app)
    
    # 挂载静态文件
    mount_static_files(app)
    
    # 记录应用创建日志
    logger.info(f"🚀 {settings.PROJECT_NAME} v{settings.PROJECT_VERSION} 应用已创建")
    
    return app


def register_events(app: FastAPI) -> None:
    """注册应用事件 📅

    Args:
        app: FastAPI应用实例
    """
    @app.on_event("startup")
    async def startup_event():
        """应用启动事件"""
        logger.info("🚀 应用正在启动...")
        
        # 记录系统启动日志
        system_logger.log_system_startup(
            version=settings.PROJECT_VERSION,
            environment=settings.ENVIRONMENT
        )
        
        # 初始化数据库
        await init_db()
        
        # 其他启动任务
        await run_startup_tasks()
        
        logger.info("✅ 应用启动完成")
    
    @app.on_event("shutdown")
    async def shutdown_event():
        """应用关闭事件"""
        logger.info("🛑 应用正在关闭...")
        
        # 关闭数据库连接
        await close_db_connections()
        
        # 其他关闭任务
        await run_shutdown_tasks()
        
        # 记录系统关闭日志
        system_logger.log_system_shutdown(0)  # 暂时不计算运行时间
        
        logger.info("✅ 应用已安全关闭")


async def run_startup_tasks() -> None:
    """运行启动任务 🏁"""
    # 这里可以添加需要在应用启动时执行的异步任务
    pass


async def run_shutdown_tasks() -> None:
    """运行关闭任务 🏁"""
    # 这里可以添加需要在应用关闭时执行的异步任务
    pass


def register_routers(app: FastAPI) -> None:
    """注册API路由 🛣️

    Args:
        app: FastAPI应用实例
    """
    # 导入API路由
    from backend.api.v1.api import api_router as api_v1_router
    from backend.api.health import health_router
    
    # 注册API路由
    app.include_router(api_v1_router, prefix=settings.API_V1_PREFIX)
    app.include_router(health_router, prefix="/health", tags=["health"])
    
    # 根路由
    @app.get("/", tags=["root"])
    async def root():
        """根路由"""
        return {
            "name": settings.PROJECT_NAME,
            "version": settings.PROJECT_VERSION,
            "description": settings.PROJECT_DESCRIPTION,
            "environment": settings.ENVIRONMENT,
            "docs": f"{settings.DOCS_URL}" if not settings.is_production else None
        }
    
    # 前端配置路由
    @app.get("/api/config", tags=["config"])
    async def frontend_config():
        """前端配置"""
        return settings.get_frontend_config()


def mount_static_files(app: FastAPI) -> None:
    """挂载静态文件 📁

    Args:
        app: FastAPI应用实例
    """
    # 挂载静态文件
    try:
        app.mount("/static", StaticFiles(directory="static"), name="static")
        app.mount("/assets", StaticFiles(directory="frontend/dist/assets"), name="assets")
        
        # 如果前端构建目录存在，则挂载
        import os
        if os.path.exists("frontend/dist"):
            app.mount("/", StaticFiles(directory="frontend/dist", html=True), name="frontend")
            logger.info("✅ 已挂载前端静态文件")
    except Exception as e:
        logger.warning(f"⚠️ 挂载静态文件失败: {e}")


# 导出所有公共函数
__all__ = [
    'create_app',
]